/**
 * 添加/编辑商品
 */
 var getImageHtml = function(imgUrl,delFunName,index,width,height){
	 console.log(width+'----------------'+height);
    return "<div class=\"am-u-sm-4 am-u-md-4\">"
          +"<img width=\"100%\" src=\""+imgUrl+"\" alt=\"商品预览图\"/><span>"+width+" * "+height+" px</span>"
          +"<div class=\"am-text-center am-text-primary am-margin-top-xs\" onclick=\""+delFunName+"(this)\">删除</div>"
          +"</div>";
 };
 var callback = function(arr){
	 var newArr = new Array();
	 for(var i=0;i<arr.length;i++){
		 if(arr[i] !=""){
			 newArr.push(arr[i]);
		 }
	 }
	 return newArr;
 }
 
 var fileChange = function(fileId){
	 var file_len = $('#banner_fileupload').prop('files').length;
   	 var url = $("#banner_img").val();
   	 var urlsArr = url.split(",");
   	 urlsArr = callback(urlsArr);
   	 var len = urlsArr.length + $('#banner_fileupload').prop('files').length;
   	 if(len > 5){
   		$('#banner_fileupload').fileupload('disable');
   		showImageInvalidAlert("最多上传5张图片");
   	 }else{
   		$('#banner_fileupload').fileupload('enable');
   	 }
   	 return true;
 }
 
 var showBannerImg = function(banner_img_urls){
    var urlsArr = banner_img_urls.split(",");
    var len = urlsArr.length;
    for(var i=0;i<len;i++){
      if(urlsArr[i]){
    	var imgWidth = 0;
    	var imgHeight = 0;
    	$.ajax({
		   type: "GET",
		   url: "imageDetail",
		   data: "url="+urlsArr[i],
		   dataType:"json",
		   async:false,
		   success: function(result){
			   imgWidth = result.imgWidth;
			   imgHeight = result.imgHeight;
		   }
    	});
        var temp = getImageHtml(urlsArr[i],"deleteBannerImg",null,imgWidth,imgHeight);
        $("#banner-img-preview #banner-img-split").before($(temp));
      }
    }
 };

/*确认是否提交*/
var confirmSubmit = function(){
  //console.log($('[name=desp_detail'));
  var isConfirm = false;
  var productSkuStr = $("#product-sku-array").val();  
  if(productSkuStr){
    var productSkuArr = JSON.parse(productSkuStr);    
    if(productSkuArr && productSkuArr.length > 0){
      if(productSkuArr[0].sku_opt_id == 0){
        //return confirm("你还没有添加商品规格或者详细描述，是否确认要提交？")
        var bd='';
        var hd = "你还没有添加商品规格或者详细描述，是否确认要提交？";
        $("#confirm-modal .am-modal-hd").html(hd);
        $("#confirm-modal .am-modal-bd").html(bd);
        $("#confirm-modal").modal({
          relatedTarget: this,
          onConfirm: function(options) {
            //$("#frm").submit();
            isConfirm = true;
            return true;
          },
          // closeOnConfirm: false,
          onCancel: function() {
            isConfirm = false;
            return false;
          }
        });
      }else{
        isConfirm = true;
        return true;
        //$("#frm").submit();
      }
    }
  }
  console.log(isConfirm);
  return isConfirm;
};

var regionsClick = function(object){
  setRegionAll();
}

var setRegionAll = function(){
  var checkedAll = true;
  $('[name = regions]:checkbox').each(function(index, el) {
    if(!el.checked){
      checkedAll = false;
    }
  });
  if(checkedAll){
    $('[name = regionsAll]:checkbox').uCheck('check');
  }else{
    $('[name = regionsAll]:checkbox').uCheck('uncheck');
  }
}

$(function() {
  //初始化富文本编辑器
  var ue = UE.getEditor('container');

  // $("#submit-btn").on("click",function(){
  //   setProductSku();

  //   confirmSubmit();
  //   // if(confirmSubmit()){
  //   //   $("#frm").submit();
  //   // }
  // });
  setRegionAll();
  $('#regionsAll').on('click', function(){
    if($('#regionsAll').prop('checked')){
      $('[name = regions]:checkbox').uCheck('check');
    }else{
      $('[name = regions]:checkbox').uCheck('uncheck');
    }
  });

	console.log("base="+base);
  /*switch开关 begin*/
  $("#status").on({
      "switchChange.bootstrapSwitch": function(event, state) {
        $status = $("input[name='status']");
        if(state) {
          $status.val(1);//0－已下架，1－已上架
        }else{
          $status.val(0);
        }
        console.log("status = " + $status.val());
      }
  });
  /*switch开关 end*/
  /*表单验证：begin*/
  var $myField = null;
  var myMsg = "";
  $("#frm").validator({
    // 域通过验证时回调
    onValid: function(validity) {
      $(validity.field).closest('.am-form-group').find('.am-alert').hide();
    },
    // 验证出错时的回调， validity 对象包含相关信息，格式通 H5 表单元素的 validity 属性
    onInValid: function(validity) {
      var $field = $(validity.field);
      var $group = $field.closest('.am-form-group');
      var $alert = $group.find('.am-alert');
      var msg = "";
      if($myField && myMsg && $field.val() && $field.is($myField)){
        msg = myMsg;
        $myField = null;
        myMsg = "";
      }else{
        // 使用自定义的提示信息 或 插件内置的提示信息
        msg = $field.data('validationMessage') || this.getValidationMessage(validity);
      }

      if (!$alert.length) {
        $alert = $("<div class='am-alert am-alert-danger'></div>").hide().
        appendTo($group.find(".input-msg"));
      }
      console.log("onInValid : "+$field.val());
      $alert.html(msg).show();
    },
    //自定义验证
    validate: function(validity) {
    	// 在这里编写你的验证逻辑
        var v = $(validity.field).val();
        var comparer = function(v1, v2) {
        	//if (v1 <= v2) {
        	if(DateTimeCompare(v1, v2)){
        		validity.valid = false;
        	}
        };
        
        if ($(validity.field).is('#put_off_time')){
        	var put_on_time = $('#put_on_time').val();
        	var put_off_time = $('#put_off_time').val();
        	comparer(put_on_time, put_off_time);
        }
    },
    submit: function() {
      var formValidity = this.isFormValid();
      var imageUrl = $("#banner_img").val();       
      if(imageUrl==null || imageUrl.length==0){
          showImageInvalidAlert("请上传商品封面图片");
          return false;
      }
      // 表单验证成功，弹出确认提示
      if (formValidity) {
        setProductSku();
        if(confirmSubmit()){
          return true;
        }       
        // if(confirm("你还没有添加商品规格或者详细描述，是否确认要提交？")){
          // return true;
        // }
      }
      console.warn('验证状态：', formValidity ? '通过' : '未通过');
      return false;
    }
  });
  
  /*表单验证：end*/
	/*商品广告图附件上传：begin*/
    var jqXHR = $('#banner_fileupload').fileupload({
      url: base+"/upload/image",
      dataType: 'json',
      start: function (e) {
    	  console.log("base="+base);
        console.log("banner_fileupload start ");
        $("#progress-area").removeClass("am-hide");
        $("#progress-text").removeClass("am-text-danger");
        $("#progress-text").html("");
        $(".am-progress-bar").css("width","0%");
      },
      done: function (e, data) {
        if(data.result.status=="error"){
        	 setTimeout(function() {
                 $("#progress-area").addClass("am-hide");
             },1500);
        	showImageInvalidAlert(data.result.message);
        	return false;
        }
        var img=$("#banner_img").val();
        $("#banner_img").val(img+data.result.url+",");
        var temp = getImageHtml(data.result.url,"deleteBannerImg",null,data.result.imgWidth,data.result.imgHeight);
        //console.log("temp="+temp);
        var pre =$(temp);
        $("#banner-img-preview #banner-img-split").before(pre);
        $("#banner-img-preview").parent().removeClass("am-hide");
        setTimeout(function() {
          $("#progress-area").addClass("am-hide");
        },1500);
        clearImageValidInfo("");
      },
      progressall: function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $(".am-progress-bar").css("width",progress + "%");
        $("#progress-text").html(progress + "%");
      },
      error: function (jqXHR, textStatus, errorThrown) {
        console.log("imageupload error！");
        // console.log(jqXHR);
        // console.log(textStatus);
        // console.log(errorThrown);
        $("#progress-area").removeClass("am-hide");
        $("#progress-text").addClass("am-text-danger");
        $("#progress-text").html("imageupload error！");
        $(".am-progress-bar").css("width","0%");
        setTimeout(function() {
          $("#progress-area").addClass("am-hide");    
        },2000);
      },
      fail: function (jqXHR, textStatus) {
        console.log("imageupload fail！");
        // console.log(jqXHR);
        // console.log(textStatus);
        $("#progress-area").removeClass("am-hide");
        $("#progress-text").addClass("am-text-danger");
        $("#progress-text").html("imageupload fail！");
        $(".am-progress-bar").css("width","0%");
        setTimeout(function() {
          $("#progress-area").addClass("am-hide");    
        },2000);
      }
    });
    /*附件上传：end*/	
	
    /*商品缩略图附件上传：begin*/
    var jqXHR = $('#thumbnail_fileupload').fileupload({
      url: base+"/upload/image/",
      dataType: 'json',
      start: function (e) {
    	  console.log("base="+base);
       console.log("banner_fileupload start ");
        $("#thumbnail-progress-area").removeClass("am-hide");
        $("#thumbnail-progress-text").removeClass("am-text-danger");
        $("#thumbnail-progress-text").html("");
        $(".thumbnail-am-progress-bar").css("width","0%");
      },
      done: function (e, data) {
        console.log("banner_fileupload done");

        $("#thumbnail").val(data.result.url);
        
        var temp = getImageHtml(data.result.url,"deleteThumbnailImg");
        //console.log("temp="+temp);
        var pre =$(temp);

        $("#thumbnail-preview").empty();
        $("#thumbnail-preview").append(pre);
        $("#thumbnail-preview").parent().removeClass("am-hide");
        setTimeout(function() {
          $("#thumbnail-progress-area").addClass("am-hide");    
        },1500);        
      },
      progressall: function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $(".thumbnail-am-progress-bar").css("width",progress + "%");
        $("#thumbnail-progress-text").html(progress + "%");
      },
      error: function (jqXHR, textStatus, errorThrown) {
        console.log("imageupload error！");
        // console.log(jqXHR);
        // console.log(textStatus);
        // console.log(errorThrown);
        $("#thumbnail-progress-area").removeClass("am-hide");
        $("#thumbnail-progress-text").addClass("am-text-danger");
        $("#thumbnail-progress-text").html("imageupload error！");
        $(".thumbnail-am-progress-bar").css("width","0%");
        setTimeout(function() {
          $("#thumbnail-progress-area").addClass("am-hide");    
        },2000);
      },
      fail: function (jqXHR, textStatus) {
        console.log("imageupload fail！");
        // console.log(jqXHR);
        // console.log(textStatus);
        $("#thumbnail-progress-area").removeClass("am-hide");
        $("#thumbnail-progress-text").addClass("am-text-danger");
        $("#thumbnail-progress-text").html("imageupload fail！");
        $(".thumbnail-am-progress-bar").css("width","0%");
        setTimeout(function() {
          $("#thumbnail-progress-area").addClass("am-hide");    
        },2000);
      }
    });
    /*附件上传：end*/	
	
  //确认选择分类
  $("#confirm-btn").on("click",function(){
    var bd='<ol class="am-breadcrumb am-breadcrumb-slash">'+ $("#breadcrumb").html()+'</ol>';
    var hd = "选择分类后将无法修改，请确认是否正确？";
    $("#confirm-modal .am-modal-hd").html(hd);
    $("#confirm-modal .am-modal-bd").html(bd);
    $("#confirm-modal").modal({
      relatedTarget: this,
      onConfirm: function(options) {
        $.each($(".am-tabs").find("li"),function(){
          if($(this).attr("id") == "sel-category"){
            $(this).addClass("am-hide")
            $(this).removeClass("am-active");
            $("#info").addClass("am-active");
            $("#category").removeClass("am-active");
          }else{
            $(this).removeClass("am-hide");
            if($(this).attr("id") == "base-info"){
              $(this).addClass("am-active");
            }
          }
        });
        $("#confirm-btns").addClass("am-hide");
        $("#submit-btns").removeClass("am-hide");
        //$("#myModal").modal('hide');

        //加载品牌信息
        //loadBrands();

        //设置sku页面所属品牌项
        setSelCategoryToSkuPage();
        alert("loadSkuSet.launch");
        //加载分类相关的sku信息
        loadSkuSet();
      },
      // closeOnConfirm: false,
      onCancel: function() {
        
      }
    });
  });

  var productid = $("#product-id").val();
  if(productid){
    //标签
    $.each($(".am-tabs").find("li"),function(){
      if($(this).attr("id") == "sel-category"){
        $(this).addClass("am-hide")
        $(this).removeClass("am-active");
        $("#info").addClass("am-active");
        $("#category").removeClass("am-active");
      }else{
        $(this).removeClass("am-hide");
        if($(this).attr("id") == "base-info"){
          $(this).addClass("am-active");
        }
      }
    });
    $("#confirm-btns").addClass("am-hide");
    $("#submit-btns").removeClass("am-hide");

    //显示图片
    var thumbnail_url = $("#thumbnail").val();
    var banner_img_urls = $("#banner_img").val();
    if(thumbnail_url){
      $("#thumbnail-preview").empty();
      var temp = getImageHtml(thumbnail_url,"deleteThumbnailImg");
      $("#thumbnail-preview").append($(temp));
      $("#thumbnail-preview").parent().removeClass("am-hide");
      //$("#thumbnail-preview").html(getImageHtml(thumbnail_url,"deleteThumbnailImg"));
    }
    if(banner_img_urls){
      showBannerImg(banner_img_urls);
      $("#banner-img-preview").parent().removeClass("am-hide");
    }

    //商品已选sku及opts，用于初始化已选sku栏及sku-opt单选按钮
    var productSku = $("#product-sku").val();
    if(productSku){
      setSelSkus(JSON.parse(productSku));
    }

    //商品已选sku-opts，用于生成表结构
    var productSkuOpt = $("#product-sku-opt").val();
    if(productSkuOpt){
      setSelSkuOpts(JSON.parse(productSkuOpt));
    }

    //商品所属分类对应的sku属性以及相应的所有sku-opt，用于初始化可选sku栏
    var productSelCateSkuOpt = $("#product-sel-cate-sku-opt").val();
    if(productSelCateSkuOpt){
      showSkus(JSON.parse(productSelCateSkuOpt));
    }
  }else{
    //加载分类信息
    //loadCategories();
    //设置sku页面所属品牌项
    setSelCategoryToSkuPage();
    //加载分类相关的sku信息
    loadSkuSet();
  }
});

function deleteBannerImg(obj) {
	console.log("deleteBannerImg");
	$obj = $(obj);
	//$("#banner-img-preview").removeChild($(this));
	var img=$("#banner_img").val();

  $("#banner_img").val(img.replace($obj.parent().find("img").attr("src")+",",""));
  
  $obj.parent().empty();
  
  if(!($("#banner_img").val())){
    $("#banner-img-preview").parent().addClass("am-hide");
  }else{
    $("#banner-img-preview").parent().removeClass("am-hide");
  }
}

function deleteThumbnailImg(obj) {
	console.log("deleteThumbnail");
	$obj = $(obj);
	//$("#banner-img-preview").removeChild($(this));
	var img=$("#thumbnail").val("");
  $obj.parent().parent().empty();
  $("#thumbnail-preview").parent().addClass("am-hide");
}
function clearImageValidInfo(){
    showImageInvalidAlert("");
}
function showImageInvalidAlert(message){
  var $alert = $("#image_valid").find('.am-alert');
  if (!$alert.length) {
    $alert = $('<div class="am-alert am-alert-danger"></div>').hide()
    $alert.appendTo($("#image_valid"));
  }
  if(message.length==0){    
    $alert.hide();
  }else{    
    $alert.text(message).show();
    setTimeout(function() {
		$alert.text(message).show();
	},50);
  }
}
